package com.cn.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cn.common.BrokerEntity;
import com.cn.file.AppendMessageResult;
import com.cn.file.AppendMessageStatus;
import org.apache.commons.lang3.StringUtils;

import java.nio.charset.Charset;
import java.util.HashSet;
import java.util.Set;

public abstract class RemotingSerializable {

    private final static Charset CHARSET_UTF8 = Charset.forName("utf-8");

    public static byte[] encode(Object t) {
        //对象转成json格式
        String json = toJson(t);
        if (StringUtils.isNotEmpty(json)) {
            return json.getBytes(CHARSET_UTF8);
        }
        return null;
    }

    public static String toJson(Object obj) {
        return JSON.toJSONString(obj, false);
    }

    public static <T> T decode(byte[] data, Class<T> c) {
        String json = new String(data, CHARSET_UTF8);
        return fromJson(json, c);
    }

    public static <T> T fromJson(String json, Class<T> c) {
        return JSON.parseObject(json, c);
    }

    public static void main(String[] args) {
        Set<BrokerEntity> set = new HashSet<>();
        set.add(new BrokerEntity().setAddress("1"));
        set.add(new BrokerEntity().setAddress("2"));
        byte[] result = encode(set);
        Set<JSONObject> s1 = decode(result, Set.class);
        for (JSONObject s : s1) {
            BrokerEntity b = s.toJavaObject(BrokerEntity.class);
            System.out.println(s);
            System.out.println(b);
        }

    }

}
